<template>
  <div class="container">
    <div class="title">
      <span>工资表</span>
      <el-date-picker
        v-model="selMonth"
        type="month"
        placeholder="选择月份"
        value-format="YYYY-MM"
        @change="getFileList"
      />
      <el-button v-if="isShow" type="primary" @click="destorySheet" size="small"
        >重新上传</el-button
      >
    </div>
    <div v-if="!isShow">
      <el-upload
        class="upload-demo"
        :action="uploadActionUrl"
        accept=".xlsx"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-change="loadExcel"
        :before-remove="beforeRemove"
        multiple
        :limit="1"
        :on-exceed="handleExceed"
        :file-list="fileList"
        :data="excdata"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">
          只能上传xlsx文件，且不超过500kb
        </div>
      </el-upload>
    </div>
    <div class="luckysheet-wrap" v-if="isShow" id="luckysheet"></div>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { getFile } from "@/api/getList.js";
import LuckyExcel from "luckyexcel";
import { exportFile } from "@/utils/axios.js";
const selMonth = ref();
const isShow = ref(false);
selMonth.value = history.state.month;
console.log(history.state);
const fileList = ref([]);
const uploadActionUrl = import.meta.env.VITE_GLOB_BASE_URL + "finance/upload";
const excdata = ref({});
const loadExcel = (file, uploadFiles) => {
  const selectedFile = file.raw ?? file;
  if (!(selectedFile instanceof File)) {
    console.error("传入了非文件对象");
    return;
  }

  if (
    selectedFile.type ===
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  ) {
    console.log("文件是xlsx类型");
  } else {
    console.error("不是xlsx文件");
    ElMessage.error("请选择xlsx类型文件");
    return;
  }
  const filename = selectedFile.name.replace(/\.[^/.]+$/, ""); // 去除文件扩展名
  const reader = new FileReader();
  reader.onload = async (e) => {
    const fileData = e.target.result;
    try {
      isShow.value = true;
      LuckyExcel.transformExcelToLucky(
        fileData,
        async (exportJson, luckysheetfile) => {
          console.log(exportJson.sheets);
          creatExcel(filename, JSON.stringify(exportJson.sheets));
        }
      );
    } catch (e) {
      console.error(e);
    }
  };

  reader.onerror = function () {
    console.error("文件上传失败！错误码" + reader.error.code);
  };

  reader.readAsArrayBuffer(selectedFile);
};

function creatExcel(title, content) {
  const options = {
    container: "luckysheet", // 设定DOM容器的id
    title: title, // 设定表格名称
    lang: "zh", // 设定表格语言
    allowCopy: false, // 是否允许拷贝
    showtoolbar: false, // 是否显示工具栏
    showinfobar: false, // 是否显示顶部信息栏
    showsheetbar: false, // 是否显示底部sheet页按钮
    showstatisticBar: false, // 是否显示底部计数栏
    sheetBottomConfig: false, // sheet页下方的添加行按钮和回到顶部按钮配置
    allowEdit: false, // 是否允许前台编辑
    enableAddRow: false, // 允许增加行
    enableAddCol: false, // 允许增加列
    userInfo: false, // 右上角的用户信息展示样式
    showRowBar: false, // 是否显示行号区域
    showColumnBar: false, // 是否显示列号区域
    sheetFormulaBar: false, // 是否显示公式栏
    enableAddBackTop: false, // 返回头部按钮
    rowHeaderWidth: 0, // 纵坐标
    columnHeaderHeight: 0, // 横坐标

    hook: {
      updated: (e) => {
        // 监听更新,并在1s后自动保存
        $("#luckysheet_info_detail_save").text("已修改");
        const title = $("#luckysheet_info_detail_input").val();
        const content = luckysheet.getAllSheets();
        // 去除临时数据,减小体积
        for (const i in content) {
          content[i].data = undefined;
        }
        console.log(title);
        console.log(content);
      },
    },
  };
  options.data = JSON.parse(content);
  options.title = title;

  window.luckysheet.create(options);
}
const handleRemove = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};
const handlePreview = (uploadFile) => {
  console.log(uploadFile);
  // isShow.value = true
  // luckysheet.create({
  //   container: 'luckysheet'// 这里需要和容器的id名称一致
  // })
};

const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(
    `一次只能上传一个文件,你上传了 ${files.length + uploadFiles.length}个!`
  );
};

const beforeRemove = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(`取消上传 ${uploadFile.name} 吗?`).then(
    () => true,
    () => false
  );
};
const destorySheet = () => {
  isShow.value = false;
  window.luckysheet.destroy();
};
const getFileList = () => {
  const data = {
    file_type: 5,
    file_month: selMonth.value,
  };
  excdata.value = {
    file_type: 5,
    month: selMonth.value,
  };
  exportFile("/finance/file/info", data).then((res) => {
    if (res.data.type === "application/json") {
      isShow.value = false;
      ElMessage.error("文件不存在，请上传！");
    } else {
      const file = new File([res.data], "XXX.xlsx", {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });
      loadExcel(file);
    }
  });
};
onMounted(() => {
  getFileList();
});
</script>

<style lang="less" scoped>
.container {
  height: calc(100vh - 142px);
  background: @mainColor;

  .title {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    align-items: center;

    span {
      margin: 1vw;
    }

    .el-button {
      margin: 1vw;
    }
  }

  .upload-demo {
    position: absolute;
    left: 50%;
    top: 50%;
  }
}

.luckysheet-wrap {
  position: sticky;
  margin: 0px;
  padding: 0px;
  width: 100%;
  height: 100%;
}
:deep(.title) {
  width: 25vw;
}
:deep(.el-upload) {
  display: flex;
  flex-direction: column;
}
</style>
